const { exec } = require("../db/mysql");
const xss = require("xss");

/**
 * 获取博客列表
 * @param {*} author 作者
 * @param {*} keyword 标题
 */
const getList = (author, keyword) => {
  let sql = `select * from blogs where 1=1 `; // where 之后为条件，1=1永远为真，目的为了占位置拼接查询条件
  if (author) {
    sql += `and author='${author}' `;
  }
  if (keyword) {
    sql += `and title like '%${keyword}%' `;
  }
  sql += `order by createtime desc;`;
  return exec(sql);
};
/**
 * 博客详情
 * @param {*} id
 */
const getDetail = (id) => {
  const sql = `select * from blogs where id='${id}'`;
  return exec(sql).then((rows) => {
    return rows[0]; // 查询返回数组
  });
};

/**
 * 新建博客
 * @param {*} blogData
 * @returns
 */
const newBlog = (blogData = {}) => {
  const title = xss(blogData.title);
  const content = xss(blogData.content);
  const author = blogData.author;
  const createTime = Date.now(); // createTime bigin 类型可以不用引号
  const sql = `
  insert into blogs (title, content, createtime, author)
  values ('${title}', '${content}', ${createTime}, '${author}');`;
  return exec(sql).then((insertData) => {
    return {
      id: insertData.insertId, // 固定格式
    };
  });
};

/**
 * 更新博客
 * @param {*} id  博客ID
 * @param {*} blogData 详情内容
 */
const updateBlog = (blogData = {}) => {
  const id = blogData.id;
  const title = xss(blogData.title);
  const content = xss(blogData.content);
  const sql = `
  update blogs set title='${title}', content='${content}' where id=${id}
`;
  return exec(sql).then((updateData) => {
    if (updateData.affectedRows > 0) {
      return true;
    }
    return false;
  });
};

/**
 * 删除
 * @param {*} id 博客ID
 * @returns
 */
const delBlog = (id, author) => {
  console.log("router del - author", author);
  const sql = `delete from blogs where id='${id}' and author='${author}';`;
  return exec(sql).then((delData) => {
    if (delData.affectedRows > 0) {
      return true;
    }
    return false;
  });
};

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
};
